package top.yudoge.dogeeditor.llm.task

import dev.langchain4j.data.segment.TextSegment
import dev.langchain4j.model.embedding.EmbeddingModel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import top.yudoge.dogeeditor.llm.config.models.ModelRegistry
import top.yudoge.dogeeditor.llm.embedding.EmbeddingStoreHolder
import top.yudoge.dogeeditor.llm.util.PromptUtils
import top.yudoge.dogeeditor.service.DeKnowledgeService

@Component
class KnowledgeSaveTask {

    @Autowired
    private lateinit var knowledgeService: DeKnowledgeService

    @Autowired
    private lateinit var modelRegistry: ModelRegistry

    @Autowired
    private lateinit var embeddingModel: EmbeddingModel

    @Autowired
    private lateinit var embeddingStoreHolder: EmbeddingStoreHolder

    @Scheduled(fixedRate = 10000)
    fun saveKnowledge() {

        var knowledgeList = knowledgeService.listAll()
        var chatModel = modelRegistry.getChatModel("qwen3-coder-plus")

        for (knowledge in knowledgeList) {
            println("Saving knowledge: ${knowledge.id}")
            var prompt = PromptUtils.loadPrompt(
                "/message_compact.template", mapOf(
                    "conversation" to knowledge.originalChatHistory
                )
            )

            var compacted_history = chatModel.chat(prompt)
            println("Compacted history: $compacted_history")

            var segment = TextSegment.from(compacted_history)
            var embed = embeddingModel.embed(segment).content()!!
            var store = embeddingStoreHolder.getStore("use_knowledge")
            store.add(embed, segment, knowledge.id.toString())

            knowledgeService.delete(knowledge.id)
            println("Saved knowledge: ${knowledge.id}")
        }

    }

}